# -*- coding: utf-8 -*-
"""
Created on Sat Jul  1 11:54:39 2017

@author: claude
"""
import pymongo
from order import Order
import Token
from  util import ErrorInfo
from time import sleep

class MongoClint():
    collection_item = 'orders'
    def __init__(self):
        self.client = pymongo.MongoClient('localhost', 27017)
        self.db = self.client.weidian
        
    def check_item_in_db(self, keyword):
        return self.db[self.collection_item].find_one({"keyword":keyword})!=None
        
    def get_item_in_db(self, keyword):
        return self.db[self.collection_item].find_one({"keyword":keyword})
        
    def save_item_to_db(self, item):
        try:
            self.db[self.collection_item].insert(item)
        except pymongo.errors.DuplicateKeyError:
            print '_id %s has been existed', item["_id"]
            #logger.debug('_id %s has been existed', item["_id"])
                
    
if __name__=="__main__":
    access_token = Token.TokenGen()
    try:
        result = Order.get_orders(access_token,order_type="",page_num=1,page_size=1,add_start="",add_end="",update_start="",update_end="",version="1.1",path="api")
    except ErrorInfo.OpenError: 
        sleep(10)
        access_token = Token.TokenGen()    
    total_pages = int(result['result']['total_num']/20)+1
    mongodb = MongoClint()
    for page_num in range(1,total_pages):
        result = Order.get_orders(access_token,order_type="",page_num=page_num,page_size=20,add_start="",add_end="",update_start="",update_end="",version="1.1",path="api")
        for x in result['result']['orders']:
            if 0:   #simple version
                item = x
            else:   #hard version
                res = Order.get_order_detail(access_token,x['order_id'])
                item = res
            item['_id'] = x['order_id']
            mongodb.save_item_to_db(item)
